/**
 * 格式化时间
 * @param time 时间字符串或时间戳
 * @returns 格式化后的时间字符串
 */
export const formatTime = (time: string | number | Date): string => {
    if (!time) return ''

    const date = new Date(time)
    const now = new Date()
    const diff = now.getTime() - date.getTime()

    // 小于1分钟
    if (diff < 60 * 1000) {
        return '刚刚'
    }

    // 小于1小时
    if (diff < 60 * 60 * 1000) {
        return `${Math.floor(diff / (60 * 1000))}分钟前`
    }

    // 小于24小时
    if (diff < 24 * 60 * 60 * 1000) {
        return `${Math.floor(diff / (60 * 60 * 1000))}小时前`
    }

    // 小于30天
    if (diff < 30 * 24 * 60 * 60 * 1000) {
        return `${Math.floor(diff / (24 * 60 * 60 * 1000))}天前`
    }

    // 大于30天，显示具体日期
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hour = String(date.getHours()).padStart(2, '0')
    const minute = String(date.getMinutes()).padStart(2, '0')

    return `${year}-${month}-${day} ${hour}:${minute}`
}

/**
 * iOS兼容的日期格式化函数
 * iOS只支持以下格式：
 * - "yyyy/MM/dd"
 * - "yyyy/MM/dd HH:mm:ss" 
 * - "yyyy-MM-dd"
 * - "yyyy-MM-ddTHH:mm:ss"
 * - "yyyy-MM-ddTHH:mm:ss+HH:mm"
 */
export const formatDateTime = (timeStr: string): string => {
    if (!timeStr) return '';

    // 处理iOS兼容性问题，将"yyyy-MM-dd HH:mm:ss"格式转换为"yyyy/MM/dd HH:mm:ss"
    let formattedTimeStr = timeStr;
    if (timeStr.includes('-') && timeStr.includes(' ')) {
        // 将"2025-06-27 02:02:06"转换为"2025/06/27 02:02:06"
        formattedTimeStr = timeStr.replace(/-/g, '/');
    }

    const date = new Date(formattedTimeStr);

    // 检查日期是否有效
    if (isNaN(date.getTime())) {
        // 如果转换失败，尝试其他格式
        try {
            // 尝试ISO格式
            const isoDate = new Date(timeStr.replace(' ', 'T'));
            if (!isNaN(isoDate.getTime())) {
                return isoDate.toLocaleString('zh-CN');
            }
        } catch (e) {
            console.error('日期格式转换失败:', timeStr);
        }
        return timeStr; // 如果都失败了，返回原始字符串
    }

    return date.toLocaleString('zh-CN');
};

/**
 * iOS兼容的相对时间格式化函数（用于列表显示）
 */
export const formatRelativeTime = (timeStr: string): string => {
    if (!timeStr) return '';

    // 处理iOS兼容性问题
    let formattedTimeStr = timeStr;
    if (timeStr.includes('-') && timeStr.includes(' ')) {
        formattedTimeStr = timeStr.replace(/-/g, '/');
    }

    const date = new Date(formattedTimeStr);

    // 检查日期是否有效
    if (isNaN(date.getTime())) {
        try {
            const isoDate = new Date(timeStr.replace(' ', 'T'));
            if (!isNaN(isoDate.getTime())) {
                const now = new Date();
                const diff = now.getTime() - isoDate.getTime();
                const days = Math.floor(diff / (1000 * 60 * 60 * 24));

                if (days === 0) {
                    return isoDate.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
                } else if (days === 1) {
                    return '昨天';
                } else if (days < 7) {
                    return `${days}天前`;
                } else {
                    return isoDate.toLocaleDateString('zh-CN');
                }
            }
        } catch (e) {
            console.error('日期格式转换失败:', timeStr);
        }
        return timeStr;
    }

    const now = new Date();
    const diff = now.getTime() - date.getTime();
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));

    if (days === 0) {
        return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
    } else if (days === 1) {
        return '昨天';
    } else if (days < 7) {
        return `${days}天前`;
    } else {
        return date.toLocaleDateString('zh-CN');
    }
}; 